package wt.hpad.activity.main;

import android.app.Activity;
import android.content.Context;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import wt.hpad.ConstantFields;
import wt.hpad.R;
import wt.hpad.dialog.SimpleDialog;
import wt.hpad.dialog.SimpleDialogHandler;
import wt.hpad.dialog.TimeLoadingDialog;
import wt.hpad.model.adapter.TableAdapter;
import wt.hpad.model.bean.Dish;
import wt.hpad.model.bean.DishDetail;
import wt.hpad.model.bean.DishType;
import wt.hpad.model.bean.TableInfo;
import wt.hpad.model.local.DBHelper;
import wt.hpad.model.remote.HttpRequest;
import wt.hpad.utils.ActivityUtil;
import wt.hpad.utils.ThreadUtil;

import static wt.hpad.ConstantFields.SHOW_ITEMS;
import static wt.hpad.utils.LogUtil.logI;

/**
 * 主界面 controller
 * Created by wt on 12.20.
 */

class MainPresenter implements MainContract.Presenter {

    private StringBuilder mStringBuilder;
    private final Activity mActivity;
    private final Context mContext;
    private MainContract.View mMainFragment;
    private List<TableInfo> mTidArr;
    private TimeLoadingDialog mLoadingDialog;
    private TableAdapter mTableAdapter;


    MainPresenter(MainContract.View mainFragment, Activity activity, Context context) {
        mMainFragment = mainFragment;
        mMainFragment.setPresenter(this);
        mActivity = activity;
        mContext = context;
    }

    @Override
    public void subscribe() {
        loadTable();
    }

    private void loadTable() {
        int height, width;
        // 数据库读数据
        List<TableInfo> tableInfos = DBHelper.queryAllTableInfo();
        boolean isUpdate = false;
        if (tableInfos != null) {
            if (mTidArr == null) {
                isUpdate = true;
                mTidArr = new ArrayList<>();

                // 适配不同尺寸屏幕
                int heightDP = ActivityUtil.getScreenHeightDP(mActivity);
                int widthDP = ActivityUtil.getScreenWidthDP(mActivity);
                logI("MainPresenter", "loadTable |  ", "width=" + widthDP);
                logI("MainPresenter", "loadTable |  ", "height=" + heightDP);
                if (widthDP > 350 && widthDP < 400 && heightDP > 630 && heightDP < 700) {
                    height = (int) (heightDP * 1.2);
                    width = (int) (heightDP * 1.2);
                } else {
                    height = (int) (heightDP * 0.5);
                    width = (int) (heightDP * 0.5);
                }
                mTableAdapter = new TableAdapter(mContext, mTidArr, height, width, 4);
            } else {
                mTidArr.clear();
            }
            mTidArr.addAll(tableInfos);
            mMainFragment.refreshTable(mTableAdapter, isUpdate, mTidArr);
        }
    }


    @Override
    public void unsubscribe() {
        mMainFragment = null;
    }

    @Override
    public void updateTableInfo(Activity activity) {
        final HttpRequest httpRequest = new HttpRequest();
        // 从服务器获取新数据,并更新数据库
        final Observer<List<TableInfo>> tableObsr = tableObsr();
        httpRequest.handleTableInfo(tableObsr);
        mLoadingDialog = new TimeLoadingDialog.Builder()
                .setActivity(activity)
                .setStartContent("操作中...")
                .setEndContent("桌台更新完成")
                .setfailContent("桌台更新失败")
                .setHandler(new SimpleDialogHandler() {
                    @Override
                    public void onConfirm() {
                    }

                    @Override
                    public void onCancel() {
                        httpRequest.stopHandlerAction();
                        tableObsr.onError(new Throwable());
                    }
                }).build();
        mLoadingDialog.start();

    }


    // 获取桌台
    private Observer<List<TableInfo>> tableObsr() {
        return new Observer<List<TableInfo>>() {

            @Override
            public void onSubscribe(Disposable d) {
                // 清理数据库
                DBHelper.deleteAllTableInfo();
            }

            @Override
            public void onNext(List<TableInfo> value) {
                // 更新数据库
                DBHelper.updateAllTableInfo(value);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                mLoadingDialog.end();
                // 刷新main界面
                loadTable();
            }
        };
    }

    @Override
    public void updateMenu(Activity activity) {

        final HttpRequest httpRequest = new HttpRequest();
        final Observer<List<Dish>> dishObsr = dishObsr();
        // 从服务器获取新数据,并更新数据库
        httpRequest.handleMenu(dishObsr);
        mLoadingDialog = new TimeLoadingDialog.Builder()
                .setActivity(activity)
                .setStartContent("操作中...")
                .setEndContent("菜单更新完成")
                .setfailContent("菜单更新失败")
                .setHandler(new SimpleDialogHandler() {
                    @Override
                    public void onConfirm() {
                    }

                    @Override
                    public void onCancel() {
                        httpRequest.stopHandlerAction();
                        dishObsr.onError(new Throwable());
                    }
                }).build();
        mLoadingDialog.start();
    }

    // 获取菜单
    private Observer<List<Dish>> dishObsr() {

        return new Observer<List<Dish>>() {
            @Override
            public void onSubscribe(Disposable d) {
                DBHelper.deleteAllMenu();
            }

            @Override
            public void onNext(List<Dish> value) {
                DBHelper.updateAllMenu(value);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                // 获取菜品分类
                new HttpRequest().handleType(typeObsr());
            }
        };
    }

    private Observer<List<DishType>> typeObsr() {
        return new Observer<List<DishType>>() {
            @Override
            public void onSubscribe(Disposable d) {
                DBHelper.deleteAllType();
            }

            @Override
            public void onNext(List<DishType> value) {
                DBHelper.updateAllType(value);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                mLoadingDialog.end();
            }
        };
    }

    @Deprecated
    @Override
    public void updateCook() {
        // 口味存到本地文件,以;隔开
        // ...未实现
    }

    @Deprecated
    @Override
    public void updateException() {
        // 原因存到本地文件,以;隔开
        // ...未实现
    }

    @Override
    public void refreshTableState() {
        final HttpRequest httpRequest = new HttpRequest();
        // 从服务器获取新数据,并更新数据库
        httpRequest.handleTableInfo(tableStateObsr());
    }

    // 获取桌台,更新桌台状态
    private Observer<List<TableInfo>> tableStateObsr() {
        return new Observer<List<TableInfo>>() {

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(List<TableInfo> value) {
                // 更新桌台状态
                for (TableInfo item : value) {
                    DBHelper.updateTableInfo(item);
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                // 刷新main界面
                loadTable();
            }
        };
    }

    @Deprecated
    @Override
    public void setDeviceID() {
        setBasicInfoByDialogEdt("device", "设备号");
    }

    @Override
    public void setServerInfo() {
        setBasicInfoByDialogEdt("server", "服务器ip");
    }

    @Override
    public void setShowItem() {
        mStringBuilder = new StringBuilder();
        final List<CheckBox> checkBoxes = new ArrayList<>();

        final SimpleDialog dialog
                = new SimpleDialog(mContext,
                mActivity,
                R.layout.dialog_checkbox,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        dialog.setTitle("桌台菜品显示项");
        View rootView = dialog.getRootView();

        final CheckBox cb_1 = (CheckBox) rootView.findViewById(R.id.cb_1);
        final CheckBox cb_2 = (CheckBox) rootView.findViewById(R.id.cb_2);
        final CheckBox cb_3 = (CheckBox) rootView.findViewById(R.id.cb_3);

        checkBoxes.add(cb_1);
        checkBoxes.add(cb_2);
        checkBoxes.add(cb_3);
        initShowCheckBox(checkBoxes);

        // "显示项"设置
        dialog.setHandler(new SimpleDialogHandler() {
            @Override
            public void onConfirm() {
                for (CheckBox item : checkBoxes) {
                    if (item.isChecked()) {
                        int i = checkBoxes.indexOf(item);
                        String value = ++i + ",";
                        mStringBuilder.append(value);
                    }
                }
                ConstantFields.setShowItems(mContext, mStringBuilder.toString());
                mStringBuilder = null;
            }

            @Override
            public void onCancel() {
            }
        });
        dialog.show();
    }

    @Override
    public void enterTable(int position) {
        ConstantFields.CURRENT_TABLE = mTidArr.get(position).tableID;
        // 请求该桌台数据
        new HttpRequest().handleEnterTable(getEntbObsr(), mTidArr.get(position).tableID);

    }

    private Observer<List<DishDetail>> getEntbObsr() {
        return new Observer<List<DishDetail>>() {

            @Override
            public void onSubscribe(Disposable d) {
            }


            @Override
            public void onNext(List<DishDetail> value) { // 这里value为null,则直接进入onComplete
                ArrayList<DishDetail> result = new ArrayList<>();
                for (DishDetail item : value) {
                    if (SHOW_ITEMS != null) {// 根据选项来过滤(退菜, 以上, 未上, 已退, 异常)
                        // 显示项过滤
                        for (int i = 0; i < SHOW_ITEMS.length; i++) {
                            if (item.dishIsCompleted == SHOW_ITEMS[i]) {
                                result.add(item);
                            }
                        }
                    } else {
                        result.add(item);
                    }
                }
                value.clear();
                value = null;
                // 进入"detail"活动
                mMainFragment.startDetailActivity(result);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                // 桌台未开
                // 打开"就餐人数"对话框
                // "确定"后
                // 进入"place"活动
                ThreadUtil.runOnUI(new Runnable() {
                    @Override
                    public void run() {
                        setPeopleNumByDialogEdt("就餐人数");
                    }
                });
            }
        };
    }


    /**
     * 用本地数据初始化"显示项"中的checkbox
     */
    private void initShowCheckBox(List<CheckBox> checkBoxes) {
        ConstantFields.initShowItems(mContext);
        if (SHOW_ITEMS != null && SHOW_ITEMS.length != 0) {
            for (CheckBox item : checkBoxes) {
                for (int i = 0; i < SHOW_ITEMS.length; i++) {
                    if (checkBoxes.indexOf(item) + 1 == SHOW_ITEMS[i]) {
                        item.setChecked(true);
                    }
                }
            }
        } else {
            for (CheckBox item : checkBoxes) {
                item.setChecked(true);
            }
        }
    }

    /**
     * "设置..."的标准对话框
     *
     * @param key sp文件中的 key->value
     */
    private void setBasicInfoByDialogEdt(final String key, String dialogTitle) {
        final SimpleDialog dialog
                = new SimpleDialog(mContext,
                mActivity,
                R.layout.dialog_edittext,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        dialog.setTitle(dialogTitle);
        View rootView = dialog.getRootView();
        final EditText edt_Content = (EditText) rootView.findViewById(R.id.edt_content);
        edt_Content.setInputType(InputType.TYPE_CLASS_NUMBER);
        setAutoPopSoftkeyboard(edt_Content, ".0123456789.");

        if (!TextUtils.isEmpty(key)) {
            String basicInfo = ConstantFields.getBasicInfo(key);
            edt_Content.setText(basicInfo);
            dialog.setHandler(new SimpleDialogHandler() {
                @Override
                public void onConfirm() {
                    String content = edt_Content.getText().toString();
                    if (TextUtils.isEmpty(content)) {
                        return;
                    }
                    ConstantFields.setBasicInfo(mContext, key, content);
                }

                @Override
                public void onCancel() {
                }
            });
        }
        dialog.show();
    }

    /**
     * 就餐人数输入
     *
     * @param dialogTitle
     */
    private void setPeopleNumByDialogEdt(String dialogTitle) {
        final SimpleDialog dialog
                = new SimpleDialog(mContext,
                mActivity,
                R.layout.dialog_edittext,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        dialog.setTitle(dialogTitle);
        View rootView = dialog.getRootView();
        final EditText edt_Content = (EditText) rootView.findViewById(R.id.edt_content);
        edt_Content.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        setAutoPopSoftkeyboard(edt_Content, "0123456789");

        dialog.setHandler(new SimpleDialogHandler() {
            @Override
            public void onConfirm() {
                String content = edt_Content.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return;
                } else {

                    ConstantFields.TEMPSTRING = content;
                    // 进入"place"活动
                    mMainFragment.startOrderActivity();
                }
            }

            @Override
            public void onCancel() {
            }
        });
        dialog.show();
    }

    // 选定所有内容,并弹出虚拟键盘
    private void setAutoPopSoftkeyboard(final EditText editText, String limitText) {
        editText.setKeyListener(DigitsKeyListener.getInstance(limitText));
        editText.setSelectAllOnFocus(true);
        new Timer().schedule(new TimerTask() {
            public void run() {
                InputMethodManager inputManager
                        = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(editText, 0);
            }

        }, 200);
    }
}
